// pages/chat/chat.ts
import { createCase } from '../../api/case';
import { getGuideList } from '../../api/guide'
import { debounce } from '../../utils/debounce'
import { flow } from '../../utils/flowtype';
import { createAssistance } from '../../api/guideai'
import { formatDate } from '../../utils/time';

Page({
  /**
   * 页面的初始数据
   */
  data: <any>{
    isEnd: false,
    active: 1,
    step1Show: true,
    step2Show: false,
    guideList: [],
    params: {
      pageNum: 1,
      pageSize: 300,
      totalNum: 10
    },
    detail: null,
    form: null,
    oldGuideName: '',
    guideName: '',
    currentGuide: '',
    currentAssistant: '',
    currentAssistantName: '',
    currentAssistantMarkdown:  [{
      content: '',
      newContent: ''
    }],
    newContent: '',
    scrollIntoViewId: '',
    editFlag: {
      name: false,
      disease: false,
      change: false,
      diagnosisTime: false,
      hospital: false,
      treatment: false,
      programme: false
    },
    btnDisable: true
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const _self = this;
    const app = getApp();
    if(app.globalData.caseUploadFileContent){
      const detail = {
        ...app.globalData.caseUploadFileContent
      }
      if(!detail.name){
        detail.name = '暂无';
      }
      if(detail.hospital){
        if(Array.isArray(detail.hospital)){
          let hospital = detail.hospital.join(',')
          detail.hospital = hospital
        }
      }
      if(detail.programme){
        if(Array.isArray(detail.programme)){
          let programme = ''
          detail.programme.forEach((element: any) => {
            programme += element.duration + ' ' + element.treatment + '\n'
          });
          detail.programme = programme
        }
      }

      if(detail.treatment){
        if(Array.isArray(detail.treatment)){
          let treatment = ''
          detail.treatment.forEach((element: any) => {
            treatment += (element.date || element.time) + ' ' + (element.description || element.details) + '\n'
          });
          detail.treatment = treatment
        }
      }
      _self.setData({
        detail,
        form: detail
      })
    }
  },

  showEditor(e){
    const { flag } = e.currentTarget.dataset;
    const editFlag: any = {};
    editFlag[flag] = true;
    this.setData({
      editFlag: editFlag
    })
  },

  backToCase(){
    wx.navigateBack({
      delta: 1  // delta 值为 1 时表示关闭当前页面
    });
  },

  backToFirst(){
    this.setData({
      step1Show: true,
      step2Show: false
    })
  },

  makeAi(){
    wx.showLoading({
      title: '加载中',
    })
    const requestTask = wx.request({
      url: 'https://aiagent.zn-care.com/api/v1/chat/completions',
      method: "POST",
      enableChunked: true,
      header: {
        "Authorization": `Bearer fastgpt-zhcFt56K6GqTPxNFyfYN0aO5yjNMiPnFPfMKKO6BjdcCgbpFobJTCp`,
        "Content-Type": "application/json",
      },
      data: {
        "stream": true,
        "variables":{"book":[this.data.currentGuide.name]},
        "messages": [
          {
            role: "user",
            content: JSON.stringify(this.data.detail),
          }
        ]
      },
      success: () => {
        wx.hideLoading()
      },
      fail: () => {
        wx.hideLoading()
      }
    })

    this.setData({
      requestTask: requestTask
    })

    requestTask.onChunkReceived((response) => {
      let result = flow(response, this.data.newContent, this.data.currentAssistantMarkdown)

      this.setData({
        currentAssistantName: this.data.currentGuide.name,
        newContent: result.newContent,
        currentAssistantMarkdown: result.answers
      })

      // 滚动
      this.throttleScrollBottom()
    });
    this.setData({
      newContent: ""
    })
  },

  sureNext(){
    if(getApp().globalData.guideList.length > 0){
      const list = getApp().globalData.guideList
      this.setData({
        guideList: list,
        searchGuideList: list
      })
    }else{
      this.getGuideListHandle()
    }

    this.setData({
      step1Show: false,
      step2Show: true
    })
  },

  sure(){
    // 保存案例
    createCase(this.data.form).then(res => {
      if(res.data.id){
        wx.showToast({
          title: '案例保存成功',
          icon: 'success',
          duration: 2000,
        })

        // 保存
        createAssistance({
          caseId: res.data.id,
          content: this.data.currentAssistantMarkdown[0].newContent,
          modelId: this.data.currentGuide.id,
          originalText: ''
        }).then(res => {
          wx.showToast({
            title: '辅助保存成功',
            icon: 'success',
            duration: 2000,
          })

          wx.switchTab({
            url: '/pages/case/case'
          });
        })
      }else{
        wx.showToast({
          title: '保存失败',
          icon: 'error',
          duration: 2000,
        })
      }
    })

    
  },

  choseGuide(e: any){
    this.setData({
      currentGuide: e.currentTarget.dataset.item,
      btnDisable: false
    })
  },

  handleInput: debounce((e: any, context: any) => {
    const value = e.detail.value;
    const { flag } = e.currentTarget.dataset
    const f: any = {}
    f[flag] = value;

    context.setData({
      form: {
        ...context.data.form,
        ...f
      }
    })
  }),

  lazySearch(e: any){
    const name = e.detail.value
    const list = this.data.guideList.filter(item => {
      return item.name.indexOf(name) > -1
    })

    this.setData({
      guideName: name,
      searchGuideList: list
    })
  },

  getGuideListHandle(){
    const query: any = {
      ...this.data.params
    }
    if(this.data.guideName){
      query.name = this.data.guideName
    }
    getGuideList(query).then(res => {
      if(typeof res.total !== 'undefined'){
        this.setData({
          params: {
            ...this.data.params,
            totalNum: res.total
          }
        })
      }
      
      if(res.rows && res.rows.length > 0){
        this.setData({
          searchGuideList: res.rows,
          guideList: res.rows
        })
        getApp().globalData.guideList = res.rows
      }else{
        this.setData({
          searchGuideList: [],
          guideList: []
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    try {
      this.data.requestTask.abort()
    } catch (error) {
      console.log('还没发请求就退出了，正常不会有影响')
    }
  },

  // markdown解析
  markdown(content: string) {
    let towxml = require('../../towxml/index')
    let result = towxml(content, 'markdown')
    return result
  },

  lastScrollTime: '',

  throttleScrollBottom() {
    const that = this;
    const step = 600;
    if (!this.data.lastScrollTime || (Date.now() - this.data.lastScrollTime) > step) {
      that.scrollBottom()
      this.data.lastScrollTime = Date.now();
    } else {
      clearTimeout(this.data.scrollTimeout);
      this.data.scrollTimeout = setTimeout(() => {
        that.scrollBottom();
      }, step - (Date.now() - this.data.lastScrollTime));
    }
  },

  scrollBottom(){
    this.setData({
      bottomId: 'dialogBottom'
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})